import axios from 'axios';
import { utilJs } from "@/utils/common.js";
import { checkApiHp } from '@/utils/apihpCheck';

const ckjrRequest = (options = {}) => {
  const {method = 'get', url = '', data = {}, headers = {}, onUploadProgress} = options;

  let urlArr = window.location.href.split('#');
  let encodeUrl = urlArr.length > 1 ? encodeURIComponent(urlArr[1]) : '';//url 为 # 后的部分（包含所有 query string）
  let userId = localStorage.getItem('userId') == '' ? -100 : localStorage.getItem('userId');
  let companyId = localStorage.getItem('companyId');
  let chl = utilJs.isIOSAppALL() ? 'ios' : utilJs.isAndroidApp() ? 'droid' : (!!utilJs.getMobileBrowserType() && utilJs.getMobileBrowserType() != 'wx' ? utilJs.getMobileBrowserType() : 'gxh'); //chl 为端名：公众号 gxh，小程序 xcx，ios，安卓 droid, pcwb  新增：抖音=dy, 快手=ks，普通浏览器=llq
  let defaultHeaders = {};

  //发送到公司内部的接口请求，需要带上默认请求头
  if (url.includes(global.apiurl)) {
    defaultHeaders = {
      'Content-Type': 'application/json',
      'X-From': 'oa',
      'Authorization':'Bearer ' + localStorage.getItem("token"),
      'X-DMP': `u=${userId}&c=${companyId}&url=${encodeUrl}&chl=${chl}`, //数据埋点标识
      'X-Trace-Ch': utilJs.getFromApplicationNum(), //渠道来源，用于用户行为轨迹分析
      'X-STORE-ID': utilJs.getStoreId()
    };
    if (localStorage.getItem("devId")) {
      defaultHeaders['X-DEVID'] = localStorage.getItem("devId");
    }
    data.fromApp = 'oa';
  }
  const config = {
    method: method,
    url:checkApiHp(url),
    headers:{...defaultHeaders, ...headers}
  };
  if (onUploadProgress) {
    config.onUploadProgress = onUploadProgress;
  }
  if (method == 'get') {
    config.params = data;
  } else {
    config.data = data;
  }
  return axios(config);
}

export {
  ckjrRequest,
};
